from application import app, db
from flask import Blueprint, request, make_response, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.DataHelper import getCurrentTime
from common.models.card_order import CardOrder
import json, requests
import urllib.request

card_page = Blueprint("card_page", __name__)


@card_page.route('/postcardorder', methods=['GET', 'POST'])
def postcardorder():
    req = request.values
    name = req['name'] if "name" in req else ""
    company = req['company'] if "company" in req else ""
    department = req['department'] if "department" in req else ""
    openid = req['openid'] if "openid" in req else ""
    city = req['city'] if "city" in req else ""
    reason = req['reason'] if "reason" in req else ""

    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入姓名")

    if len(company) < 1 or company == "请选择":
        return ops_renderErrJSON(msg="请选择公司名称")

    if len(department) < 1 or department == "请选择":
        return ops_renderErrJSON(msg="请选择部门")

    if len(reason) < 1 or reason == "请选择":
        return ops_renderErrJSON(msg="请选择原因")

    if len(city) < 1 or city == "请选择":
        return ops_renderErrJSON(msg="请选择城市")

    else:
        Order = CardOrder()
        Order.name = name
        Order.company = company
        Order.department = department
        Order.city = city
        Order.openid = openid
        Order.reason = reason
        Order.mark = 1
        Order.created_time = Order.updated_time = getCurrentTime()

        db.session.add(Order)
        db.session.commit()

        return json.dumps({"code": 200, "msg": "申请成功", }, indent=4,
                          sort_keys=True, default=str,
                          ensure_ascii=False)


# 管理员获得申请列表
@card_page.route("/showcardorder", methods=["GET", "POST"])
def showcardorder():
    req = request.values
    city = req['city'] if "city" in req else ""

    a = CardOrder.query.filter(CardOrder.mark == 1, CardOrder.city == city).all()
    rts = []
    for item in a:
        temp = dict(name=item.name, company=item.company, department=item.department, reason=item.reason, id=item.id,
                    openid=item.openid)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@card_page.route('/pushmessage', methods=['GET', 'POST'])
def pushMessage():
    req = request.values
    openid = req['openid'] if "openid" in req else ""
    id = req['id'] if "id" in req else ""

    appID = 'wx15624353af4493ad'  # 开发者关于微信小程序的appID
    appSecret = 'd7f09203305d4afe4716c0bdaa6fe7c7'  # 开发者关于微信小程序的appSecret
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'grant_type': "client_credential"
    }
    wx_login_api = 'https://api.weixin.qq.com/cgi-bin/token?'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    token = resData['access_token']  # 得到用户关于当前小程序的OpenID

    data = {
        "touser": openid,
        "template_id": "_pmRmKv-fT2U89V5UiPexzJMLuXKTqkANilRYm_yfLI",
        "page": "index",
        "miniprogram_state": "developer",
        "lang": "zh_CN",
        "data": {
            "thing1": {
                "value": "工卡制作完成"
            },
            "thing5": {
                "value": "请前往人事行政部领取"
            },
        }
    }

    url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={serverToken}'.format(
        serverToken=token)
    # 数据格式化(从这里开始对上面的data进行格式化,转成符合post的json参数形式)
    data = json.dumps(data)
    # 数据格式化
    data = bytes(data, 'utf8')
    # 数据格式化

    request1 = urllib.request.Request(url)
    # post服务器请求
    result = urllib.request.urlopen(request1, data).read()

    # 打印结果
    newresult = json.loads(result)
    errcode = newresult['errcode']
    if errcode == 0:
        # id = req['id'] if "id" in req else ""
        a = CardOrder.query.filter_by(id=id).all()
        for item in a:
            item.mark = 2
            db.session.commit()
        return ops_renderJSON(msg="通知成功")

    if errcode == 43101:
        # id = req['id'] if "id" in req else ""
        a = CardOrder.query.filter_by(id=id).all()
        for item in a:
            item.mark = 0
            db.session.commit()
        return ops_renderJSON(msg="员工拒绝接受通知")


@card_page.route('/pushdeny', methods=['GET', 'POST'])
def pushDeny():
    req = request.values
    openid = req['openid'] if "openid" in req else ""
    id = req['id'] if "id" in req else ""

    appID = 'wx15624353af4493ad'  # 开发者关于微信小程序的appID
    appSecret = 'd7f09203305d4afe4716c0bdaa6fe7c7'  # 开发者关于微信小程序的appSecret
    req_params = {
        'appid': appID,
        'secret': appSecret,
        'grant_type': "client_credential"
    }
    wx_login_api = 'https://api.weixin.qq.com/cgi-bin/token?'
    response_data = requests.get(wx_login_api, params=req_params)  # 向API发起GET请求
    resData = response_data.json()
    token = resData['access_token']  # 得到用户关于当前小程序的OpenID

    data = {
        "touser": openid,
        "template_id": "_pmRmKv-fT2U89V5UiPexzJMLuXKTqkANilRYm_yfLI",
        "page": "pages/index/index",
        "miniprogram_state": "formal",
        "lang": "zh_CN",
        "data": {
            "thing1": {
                "value": "不符合制卡条件"
            },
            "thing5": {
                "value": "详情请咨询人事行政部"
            },
        }
    }

    url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={serverToken}'.format(
        serverToken=token)
    # 数据格式化(从这里开始对上面的data进行格式化,转成符合post的json参数形式)
    data = json.dumps(data)
    # 数据格式化
    data = bytes(data, 'utf8')
    # 数据格式化

    request1 = urllib.request.Request(url)
    # post服务器请求
    result = urllib.request.urlopen(request1, data).read()
    # 打印结果
    newresult = json.loads(result)
    errcode = newresult['errcode']
    if errcode == 0:
        # id = req['id'] if "id" in req else ""
        a = CardOrder.query.filter_by(id=id).all()
        for item in a:
            item.mark = 0
            db.session.commit()
        return ops_renderJSON(msg="通知成功")

    if errcode == 43101:
        # id = req['id'] if "id" in req else ""
        a = CardOrder.query.filter_by(id=id).all()
        for item in a:
            item.mark = 0
            db.session.commit()
        return ops_renderJSON(msg="员工拒绝接受通知")
